package com.bird.thread.base.thread;

/**
 * @author sijunqiang
 * @data 2021/7/2 22:49
 * @description: 功能：实现让 Thread.yield()让出自己的时间片。
 */
public class Yield {
    public static void main(String[] args) {

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程：" + Thread.currentThread().getName() + " 准备执行yield " + "线程的状态：" + Thread.currentThread().getState());
                Thread.yield();
                System.out.println("线程：" + Thread.currentThread().getName() + " 执行后yield " + "线程的状态：" + Thread.currentThread().getState());
            }
        });


        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程：" + Thread.currentThread().getName() + " 争取到了CPU的时间片" + "线程的状态：" + Thread.currentThread().getState());
                // Thread.yield();
                //  System.out.println("线程：" + Thread.currentThread().getName() + " 执行后yield " + "线程的状态：" + Thread.currentThread().getState());
            }
        });

        thread1.start();

        thread2.start();
    }

    /*总结：Thread.yield()让出自己的时间片。
     * 当当前执行线程执行Thread.yield()方法时候那么这个线程就会释放cpu时间片，让其它的线程争抢资源 也包括它自己争抢。
     * 谁抢到资源谁就先执行。
     *
     *
     */
}
